import os
# import os.path as osp
import logging
# import argparse
from pathlib import Path

from utils.log import get_logger
# from yolov3_deepsort import VideoTracker
# from .deepsort import VideoTracker

# from utils.parser import get_config

import motmetrics as mm
mm.lap.default_solver = 'lap'
from utils.evaluation import Evaluator


def mkdir_if_missing(dir):
    os.makedirs(dir, exist_ok=True)


def main(data_root,seqs):
    logger = get_logger()
    logger.setLevel(logging.INFO)
    data_type = 'mot'
    result_root = os.path.join(Path(data_root), "mot_results")
    mkdir_if_missing(result_root)

    # run tracking
    accs = []
    for seq in seqs:
        logger.info('Start seq: {}'.format(seq))
        result_filename = os.path.join(result_root, '{}.txt'.format(seq))
        logger.info("seq result file path : {}".format(result_filename))
        # eval
        logger.info('Evaluate seq: {}'.format(seq))
        evaluator = Evaluator(data_root, seq, data_type)
        seq_acc = evaluator.eval_file(result_filename)
        accs.append(seq_acc)
    
    # get summary
    logger.info("Get summary")
    metrics = mm.metrics.motchallenge_metrics
    mh = mm.metrics.create()
    summary = Evaluator.get_summary(accs, seqs, metrics)
    strsummary = mm.io.render_summary(
        summary,
        formatters=mh.formatters,
        namemap=mm.io.motchallenge_metric_names
    )
    print(strsummary)
    Evaluator.save_summary(summary, os.path.join(result_root, 'summary_global.xlsx'))


if __name__ == '__main__':

    seqs_str = '''test01      
                  '''        
    data_root = 'dataset/'

    seqs = [seq.strip() for seq in seqs_str.split()]
    print(f"seqs = {seqs}")

    main(data_root=data_root,seqs=seqs)

